import { defineStore } from 'pinia'
import { ref } from 'vue'
import { apiService } from '@/services/api'

export const useUsersStore = defineStore('users', () => {
  const users = ref([])

  // 初始化用户数据
  const initializeUsers = async () => {
    try {
      users.value = await apiService.getUsers()
    } catch (error) {
      console.error('初始化用户数据失败:', error)
    }
  }

  // 根据用户名获取用户
  const getUserByUsername = async (username) => {
    try {
      return await apiService.getUserByUsername(username)
    } catch (error) {
      console.error('获取用户失败:', error)
      return null
    }
  }

  // 验证用户
  const validateUser = async (username, password) => {
    try {
      const user = await apiService.getUserByUsername(username)
      return user && user.password === password ? user : null
    } catch (error) {
      console.error('验证用户失败:', error)
      return null
    }
  }

  const enrollCourse = async (userId, courseId) => {
    try {
      const user = users.value.find(u => u.id === userId)
      if (user && user.role === 'student') {
        if (!user.enrolledCourses) {
          user.enrolledCourses = []
        }
        if (!user.enrolledCourses.includes(courseId)) {
          user.enrolledCourses.push(courseId)
          await apiService.updateUser(userId, { enrolledCourses: user.enrolledCourses })
          return true
        }
      }
      return false
    } catch (error) {
      console.error('选课失败:', error)
      throw error
    }
  }

  // 获取用户已选课程ID列表
  const getUserEnrolledCourses = (userId) => {
    const user = users.value.find(u => u.id === userId)
    return user && user.enrolledCourses ? user.enrolledCourses : []
  }

  // 学生退课
  const dropCourse = async (userId, courseId) => {
    try {
      const user = users.value.find(u => u.id === userId)
      if (user && user.role === 'student' && user.enrolledCourses) {
        const courseIndex = user.enrolledCourses.indexOf(courseId)
        if (courseIndex > -1) {
          user.enrolledCourses.splice(courseIndex, 1)
          await apiService.updateUser(userId, { enrolledCourses: user.enrolledCourses })
          return true
        }
      }
      return false
    } catch (error) {
      console.error('退课失败:', error)
      throw error
    }
  }

  return {
    users,
    initializeUsers,
    getUserByUsername,
    validateUser,
    enrollCourse,
    getUserEnrolledCourses,
    dropCourse
  }
})